import 'package:ecy_app_flutter/ecycommon/utils/EcyRandomUtil.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/exchange_user_group.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/exchange_card.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/service/exchange_service.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/pages/EcyExchangeApplyPage.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/pages/ExchangeRequestListPage.dart';

class BlindBoxMyexchange extends StatefulWidget {
  final int initialTabIndex;
  // final ExchangeCard card;   
  
  BlindBoxMyexchange({
    super.key,
    this.initialTabIndex = 0,
    ExchangeCard? card,
    List<ExchangeUserGroup>? userGroups,
  });
  
  get card => null;

  @override
  _BlindBoxMyexchangeState createState() => _BlindBoxMyexchangeState();
}
  
class _BlindBoxMyexchangeState extends State<BlindBoxMyexchange> with SingleTickerProviderStateMixin  {
  final ExchangeService _exchangeService = ExchangeService();
  late TabController _tabController;
  List<ExchangeUserGroup> userGroups = 
  [ExchangeUserGroup(userName: "userName", userAvatar: EcyRandomUtil.randomIconUrl(), 
  offerCards: [ExchangeCard(id: 0, name: "1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)], 
  wantCards: [ExchangeCard(id: 1, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false),ExchangeCard(id: 2, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false)],
   canExchange: null),
   ExchangeUserGroup(userName: "userName", userAvatar: EcyRandomUtil.randomIconUrl(), 
  offerCards: [ExchangeCard(id: 0, name: "1", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true)], 
  wantCards: [ExchangeCard(id: 1, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false),ExchangeCard(id: 2, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: false)],
   canExchange: true)];
  ExchangeCard card = ExchangeCard(id: 0, name: "123", imageUrl: EcyRandomUtil.randomIconUrl(), expiryTime: null, owned: true);
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.index = widget.initialTabIndex;
    // _loadUserGroups();
  }

  // Future<void> _loadUserGroups() async {
  //   final groups = await _exchangeService.getUserGroups(widget.card?.id ?? 0);
  //   setState(() {
  //     userGroups = groups;
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          backgroundColor: Color(0xFFF5F5F5),
          appBar: AppBar(
                    centerTitle: true,
                    backgroundColor: Colors.white,
                    elevation: 0,
                    leading: IconButton(
                      icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                    title: const Text(
                      '我的交换',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 18,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
          body: Container(
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                        decoration: BoxDecoration(
                          color: Colors.white,
                        ),
                        child: TabBar(
                          tabAlignment: TabAlignment.start,
                          isScrollable: true,
                          controller: _tabController,
                          overlayColor: MaterialStateProperty.all(Colors.transparent),
                          tabs: const [
                            Tab(text: '我上架的'),
                            Tab(text: '我申请的'),
                          ],
                          labelColor: Colors.black,
                          unselectedLabelColor: Colors.grey,
                          labelStyle: const TextStyle(
                            fontWeight: FontWeight.w500,
                            fontSize: 14,
                          ),
                          unselectedLabelStyle: const TextStyle(
                            fontWeight: FontWeight.normal,
                            fontSize: 14,
                          ),
                          indicatorColor: const Color.fromARGB(255, 246, 46, 189), // indicator 只是选中的那一段线
                          dividerColor: Colors.transparent,
                        ),
                      ),
                      
                        Expanded(
                          child: TabBarView(                            
                            controller: _tabController,
                            children: [
                              ListView.builder(
                                itemCount: userGroups.length,
                                itemBuilder: (context, index) {
                                return _buildMyshelves(userGroups[index], context);
                                }
                              ),
                              ListView.builder(
                                itemCount: userGroups.length,
                                itemBuilder: (context, index) {
                                return _buildMyapply(userGroups[index]);
                                }
                              ),
                            ],
                          ),
                        ),
                      ]
                  ),
                )
    );
  }
}

String _formatExpiryTime(DateTime expiryTime) {
  final duration = expiryTime.difference(DateTime.now());
  final days = duration.inDays;
  final hours = duration.inHours % 24;
  final minutes = duration.inMinutes % 60;
  return '${days}天${hours}小时${minutes}分钟';
}


Widget _buildMyapply(ExchangeUserGroup group) {
  int status = group.canExchange == null ? 0 : (group.canExchange! ? 1 : 2);

  String statusText;
  Color statusColor;
  switch (status) {
    case 1:
      statusText = "恭喜你，交换成功！可在\"我的痛柜\"中查看";
      statusColor = Color(0xFF00C853); // 绿色
      break;
    case 2:
      statusText = "很抱歉，对方拒绝与你交换，再看看其他的吧";
      statusColor = Color(0xFFBDBDBD); // 灰色
      break;
    default:
      statusText = "已向ta发出互换申请,请耐心等待";
      statusColor = Color(0xFFF62EBD); // 粉色
  }

  return Card(
    elevation: 0,
    margin: EdgeInsets.symmetric(vertical: 8, horizontal: 12),
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
    color: Color(0xFF5368F7).withOpacity(0.1), // 外层淡紫色背景
    child: Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          // 头像行
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 自己头像
              CircleAvatar(
                backgroundImage: NetworkImage(group.userAvatar ?? ''),
                radius: 22,
              ),
              SizedBox(width: 96),
              // 对方头像（你可以换成 group.targetAvatar）
              CircleAvatar(
                backgroundImage: NetworkImage(group.userAvatar ?? ''),
                radius: 22,
              ),
            ],
          ),
          SizedBox(height: 8),
          // 白色内容框
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
            ),
            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 8),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                // 我想用
                Column(
                  
                  children: [
                    Text('我想用', style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
                    SizedBox(height: 4),
                    _buildCardItem(group.offerCards.first, owned: true),
                  ],
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 25),
                  child: Icon(Icons.swap_horiz, color: Color(0xFFF62EBD), size: 32),
                ),
                // 与ta交换
                Column(
                  children: [
                    Text('与ta交换', style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
                    SizedBox(height: 4),
                    _buildCardItem(group.wantCards.first, owned: false),
                  ],
                ),
                
                ]
                ),
                SizedBox(height: 12),
                Text(
                  statusText,
                  style: TextStyle(fontSize: 13, color: statusColor),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
          
        ],
      ),
    ),
  );
}
  

Widget _buildMyshelves(ExchangeUserGroup group, BuildContext context) {
  return GestureDetector(
    onTap: () {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => ExchangeRequestListPage(),
        ),
      );
    },
    child: Card(
      child: Container(
        margin: EdgeInsets.zero,
        padding: EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Column(
                  children: [
                    Text('我要换出', style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
                    SizedBox(height: 4),
                    Row(
                      children: group.offerCards.map((card) => _buildCardItem(card, owned: card.owned)).toList(),
                    ),
                  ],
                ),
                SizedBox(width: 32),
                Container(
                  width: 1,
                  height: 36,
                  color: Color(0xFFD9D9D9),
                  margin: EdgeInsets.only(top: 35),
                ),
                SizedBox(width: 32),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('我想换入', 
                    style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
                    SizedBox(height: 4),
                    Row(
                      children: group.wantCards.map((card) => Padding(
                        padding: const EdgeInsets.only(right: 8.0),
                        child: _buildCardItem(card, owned: card.owned),
                      )).toList(),
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    ),
  );
}

Widget _buildCardItem(ExchangeCard card, {bool owned = false}) {
  return Column(
    children: [
      // 卡片图片
      Stack(
        alignment: Alignment.center,
        children: [
          Image.network(card.imageUrl ?? EcyRandomUtil.randomIconUrl(), width: 50, height: 59),
      
          // if (!owned)
          //   Container(
          //     width: 60,
          //     height: 60,
          //     alignment: Alignment.center,
          //     child: Text('您暂未拥有', style: TextStyle(color: Colors.white, fontSize: 10)),
          //     decoration: BoxDecoration(
          //                   color: Colors.black.withOpacity(0.5),
          //                   borderRadius: BorderRadius.circular(4), // 圆角半径 12
          //               ),
          //   ),
        ]
      ),
      
        Text(card.name, style: TextStyle(fontSize: 12, color: Color(0xFF262626))),
    ],
  );
} 